<template>
  <div class="contain-login">
    <el-card class="box-card">
      <template #header>
        <div>面经运营后台</div>
      </template>
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" type="password" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item class="center">
          <el-button type="primary" @click="submit">登录</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { authLogin } from '@/api/user'
export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' },
          { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'change' }
        ],
        password: [
          [
            { required: true, message: '请输入密码', trigger: 'change' },
            { pattern: /^\w{4,12}$/, message: '长度在 4 到 12 个字符', trigger: 'change' }
          ]
        ]
      }
    }
  },
  methods: {
    submit() {
      this.$refs.form.validate(async (result) => {
        if (result) {
          console.log('校验成功')
          console.log(this.form)
          const res = await authLogin(this.form)
          console.log(res.data.token)
          this.$store.commit('setUserToken', res.data.token)
          this.$message.success('登录成功')
          this.$router.push('/article')
        } else {
          console.log('校验失败')
          // 错误的提示信息一般由后台提供所以在响应拦截器统一处理
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.contain-login {
  height: 100vh;
  background: url('@/assets/login-bg.svg') no-repeat center;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  .box-card {
    width: 450px;
    ::v-deep .el-card__header {
      background-color: rgb(98, 108, 247);
      color: #fff;
      text-align: center;
      font-size: 18px;
      padding: 26px 0;
    }
    .center {
      text-align: center;
    }
  }
}
</style>
